package top.pro51.bolg_admin.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import top.pro51.bolg_admin.domain.Blog;
import top.pro51.bolg_admin.domain.Tag;
import top.pro51.bolg_admin.domain.Type;
import top.pro51.bolg_admin.service.BlogService;
import top.pro51.bolg_admin.service.TagService;
import top.pro51.bolg_admin.service.TypeService;

import java.util.List;


@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    /**
     * @Description 首页博客信息展示
     * @Author WangWenpeng
     * @Date 15:12 2020/7/28
     * @Param [pageable, model]
     */
    @GetMapping("/")
    public String toIndex(@RequestParam(required = false, defaultValue = "1", value = "pagenum") int pagenum, Model model) {

        PageHelper.startPage(pagenum, 10);
        List<Blog> allBlog = blogService.getIndexBlog();
        List<Type> allType = typeService.getBlogType();  //获取博客的类型(联表查询)
        List<Tag> allTag = tagService.getBlogTag();  //获取博客的标签(联表查询)
        List<Blog> recommendBlog = blogService.getAllRecommendBlog();  //获取推荐博客

        //得到分页结果对象
        PageInfo pageInfo = new PageInfo(allBlog);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("tags", allTag);
        model.addAttribute("types", allType);
        model.addAttribute("recommendBlogs", recommendBlog);
        return "index";
    }


    /**
     * @Description 右上角查询方法标题或者描述 不察 后续换Elasticsearch
     * @Author WangWenpeng
     * @Date 8:50 2020/7/30
     * @Param [pagenum, query, model]
     */
    @PostMapping("/search")
    public String search(@RequestParam(required = false, defaultValue = "1", value = "pagenum") int pagenum,
                         @RequestParam String query, Model model) {

        PageHelper.startPage(pagenum, 10);
        List<Blog> searchBlog = blogService.getSearchBlog(query);
        PageInfo pageInfo = new PageInfo(searchBlog);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("query", query);
        return "search";
    }

    /**
     * @Description 跳转博客详情页面
     * @Author WangWenpeng
     * @Date 16:14 2020/7/28
     * @Param [id, model]
     */
    @GetMapping("/blog/{id}")
    public String toLogin(@PathVariable Long id, Model model) {
        Blog blog = blogService.getDetailedBlog(id);
        model.addAttribute("blog", blog);
        return "blog";
    }
}
